import random
import datetime

from dateutil.parser import parse
from flask import Blueprint, render_template, request
from applications.common import curd
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import PoliceModels, Role, Dept, Title, Position
from applications.schemas import PoliceOutSchema

police_bp = Blueprint('adminPolice', __name__, url_prefix='/admin/police')


# 管理员信息
@police_bp.get('/')
def police_main():
    return render_template('admin/police/main.html')


#   用户分页查询1
@police_bp.get('/data')
def data():
    # 获取请求参数
    code = request.args.get('code', type=str)
    name = request.args.get('name', type=str)
    sex = request.args.get('sex', type=int)
    birthday = request.args.get('birthday', type=str)
    id_number = request.args.get('id_number', type=str)
    native_place = request.args.get('native_place', type=str)
    address = request.args.get('address', type=str)
    post = request.args.get('post', type=str)
    title = request.args.get('title', type=str)

    # 查询参数构造
    mf = ModelFilter()
    if code:
        mf.exact(field_name="code", value=code)
    if name:
        mf.contains(field_name="name", value=name)
    if sex:
        mf.contains(field_name="sex", value=sex)
    if birthday:
        mf.contains(field_name="birthday", value=birthday)
    if id_number:
        mf.contains(field_name="id_number", value=id_number)
    if native_place:
        mf.contains(field_name="native_place", value=native_place)
    if address:
        mf.contains(field_name="address", value=address)
    if post:
        mf.contains(field_name="post", value=post)
    if title:
        mf.contains(field_name="title", value=title)
    # orm查询
    # 使用分页获取data需要.items
    policeModels = PoliceModels.query.filter(mf.get_filter(model=PoliceModels)).layui_paginate()
    count = policeModels.total
    polices = model_to_dicts(schema=PoliceOutSchema, data=policeModels.items)
    return table_api(data=polices, count=count)


# 用户增加
@police_bp.get('/add')
def add():
    return render_template('admin/police/add.html')


@police_bp.post('/save')
def save():
    req_json = request.json
    print(req_json)
    dept_id = req_json.get("deptId")
    code = xss_escape(req_json.get('code'))
    name = xss_escape(req_json.get('name'))
    birthday = xss_escape(req_json.get('birthday'))
    id_number = xss_escape(req_json.get('id_number'))
    native_place = xss_escape(req_json.get('native_place'))
    address = xss_escape(req_json.get('address'))
    uwb_sn = xss_escape(req_json.get('uwb_sn'))
    gps_sn = xss_escape(req_json.get('gps_sn'))
    sign_sn = xss_escape(req_json.get('sign_sn'))

    # 获取性别信息，如果没有选择则默认为None
    try:
        sex = int(req_json.get('sex'))
    except:
        sex = None

    if sex == 0:
        gender = '男'
    elif sex == 1:
        gender = '女'
    else:
        gender = ''

    # 获取警衔信息，如果没有填写警衔则id为-1
    try:
        title_id = int(req_json.get('titleId'))
    except:
        title_id = -1
    title = Title.query.filter_by(id=title_id).one_or_none()

    # 获取职位信息，如果没有选择职位则默认为None
    try:
        position_id = int(req_json.get('position'))
    except:
        position_id = None
    position = Position.query.filter_by(id=position_id).one_or_none()

    if not code or not name:
        return fail_api(msg="账号姓名不得为空")

    dept = Dept.query.filter_by(id=dept_id).one_or_none()

    if dept is None:
        return fail_api(msg='找不到部门信息')

    if title is None:
        title_id = -1
        title = Title.query.filter_by(id=title_id).one_or_none()

    title_name = title.title_name

    # 如果没有选择职位，则职位名称为空
    if position is None:
        position_name = ''
    else:
        position_name = position.position_name


    # 添加警员信息
    user = PoliceModels(code=code,
                        name=name,
                        sex=gender,
                        birthday=birthday,
                        id_number=id_number,
                        native_place=native_place,
                        address=address,
                        post=position_name,
                        title=title_name,
                        dept_id=dept.id,
                        title_id=title_id,
                        post_id=position_id,
                        uwb_sn=uwb_sn,
                        gps_sn=gps_sn,
                        sign_sn=sign_sn)
    db.session.add(user)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除用户
@police_bp.delete('/remove/<int:id>')
def delete(id):
    user = PoliceModels.query.filter_by(id=id).first()
    user.role = []
    res = PoliceModels.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


#  编辑用户
@police_bp.get('/edit/<int:id>')
def edit(id):
    user = curd.get_one_by_id(PoliceModels, id)
    title = Title.query.filter_by(title_name=user.title).one_or_none()
    if title is None:
        title_id = -1
    else:
        title_id = title.id

    if user.sex == '男':
        gender = '0'
    elif user.sex=='女':
        gender = '1'
    else:
        gender = ''

    return render_template('admin/police/edit.html', user=user, titleId=title_id, gender=gender)


#  编辑用户
@police_bp.put('/update')
def update():
    req_json = request.json
    a = xss_escape(req_json.get("roleIds"))
    id = xss_escape(req_json.get("id"))
    id_number = xss_escape(req_json.get("id_number"))
    dept_id = req_json.get("deptId")
    code = xss_escape(req_json.get("code"))
    birthday = xss_escape(req_json.get('birthday'))
    address = xss_escape(req_json.get('address'))
    native_place = xss_escape(req_json.get('native_place'))
    dept = Dept.query.filter_by(id=dept_id).one_or_none()

    # 获取性别信息，如果没有选择则默认为None
    try:
        sex = int(req_json.get('sex'))
    except:
        sex = None

    if sex == 0:
        gender = '男'
    elif sex == 1:
        gender = '女'
    else:
        gender = ''

    if dept is None:
        return fail_api(msg='部门信息不存在')
    title_id = int(req_json.get('titleId'))
    title = Title.query.filter_by(id=title_id).one_or_none()
    if title is None:
        title_id = -1
        title = Title.query.filter_by(id=title_id).one_or_none()
    title_name = title.title_name

    try:
        position_id = int(req_json.get('position'))
    except:
        position_id = None
    position = Position.query.filter_by(id=position_id).one_or_none()
    if position is not None:
        position_name = position.position_name
    else:
        position_name = ''


    PoliceModels.query.filter_by(id=id).update({'code': code,
                                                'birthday': birthday,
                                                'sex': gender,
                                                'id_number': id_number,
                                                'native_place': native_place,
                                                'address': address,
                                                'post': position_name,
                                                'title': title_name,
                                                'dept_id': dept.id,
                                                'title_id': title_id,
                                                'post_id': position_id})

    db.session.commit()
    return success_api(msg="更新成功")


# 批量删除
@police_bp.delete('/batchRemove')
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        user = PoliceModels.query.filter_by(id=id).first()
        user.role = []

        res = PoliceModels.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


@police_bp.get('/getOne/<code>')
def getPoliceByCode(code):
    police = PoliceModels.query.filter_by(code=code).one_or_none()
    if police is None:
        return fail_api(msg="警员不存在")
    else:
        outSchema = PoliceOutSchema()
        police_schema = outSchema.dump(police)
        res = {
            "msg": "查询成功",
            "code": 0,
            "success": True,
            "data":
                {"police": police_schema}
        }
        return res


@police_bp.get('/hasuwb/<sn>')
def getuwbBySN(sn):
    res = {
        "msg": "查询成功",
        "code": 0,
        "success": True,
        "exists": False
    }
    if sn == '' or sn is None or sn.isspace():
        return res
    police = PoliceModels.query.filter_by(uwb_sn=sn).one_or_none()
    if police is None:
        return res
    else:
        res['exists'] = True
        return res


@police_bp.get('/hasgps/<sn>')
def getgpsBySN(sn):
    res = {
        "msg": "查询成功",
        "code": 0,
        "success": True,
        "exists": False
    }
    if sn == '' or sn is None or sn.isspace():
        return res
    police = PoliceModels.query.filter_by(gps_sn=sn).one_or_none()
    if police is None:
        return res
    else:
        res['exists'] = True
        return res


@police_bp.get('/hassign/<sn>')
def getsignBySN(sn):
    res = {
        "msg": "查询成功",
        "code": 0,
        "success": True,
        "exists": False
    }
    if sn == '' or sn is None or sn.isspace():
        return res
    police = PoliceModels.query.filter_by(sign_sn=sn).one_or_none()
    if police is None:
        return res
    else:
        res['exists'] = True
        return res
